import * as API from '../../../api/commodity';
import * as util from '../../../utils/util';
import { baseUrl } from "../../../config";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [],
    showTradePicker: false,
    tempTrade: null,
    showPicker: '',
    id: null,
    form: {
      commodityName: null,
      commodityIntroduce: null,
      commodityImg:null,
      lunchBoxPrice: null,
      sort: null,
      limits: null,
      grounding: false,
      commodityTypeId: null,
      commodityTypeName: null,
      commoditySpecificationsDtos: [] // 规格
    },
  },
  toCommodityStock(options){
    let commoditySpecificationsDtos = JSON.stringify(this.data.form.commoditySpecificationsDtos)
    var url = options.currentTarget.dataset.url+'?commoditySpecificationsDtos='+commoditySpecificationsDtos;
      util.preventMoreClick (this, () => {
        wx.navigateTo ({
          url: url,
        });
      });
  },
  openTradePicker: function () {
    this.setData({
      showTradePicker: true,
      showPicker: 'show',
      tempTrade: this.data.dataList[0]
    })
  },
  bindChangeTrade: function (e) {
    var tempTrade = this.data.dataList[e.detail.value[0]];
    console.log(e, 9999)
    this.setData({
      tempTrade: tempTrade
    })
  },
  closePicker: function () {
    this.setData({
      showTradePicker: false,
      showPicker: ""
    })
  },
  cancelChange: function (e) {
    this.setData({
      showTradePicker: false,
      tempTrade: null,
      showPicker: ''
    })
  },
  ensureChange: function (e) {
    let commodityTypeId = 'form.commodityTypeId'
    let commodityTypeName = 'form.commodityTypeName'
    this.setData({
      showTradePicker: false,
      [commodityTypeId]: this.data.tempTrade.id,
      [commodityTypeName]: this.data.tempTrade.commodityTypeName
    })
  },
  uploadImg() {
    let that = this
    const token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '正在上传',
        })
        let tempFilePaths = res.tempFilePaths
        if (res.tempFiles[0].size > 4096) {
          wx.hideLoading();
          wx.showToast({
            icon: 'none',
            title: '单张张片超过4M,请重新添加'
          });
          return
        } else {
          wx.uploadFile({
            url: baseUrl + '/app/upload', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            header: { 'Authorization': token},
            name: 'files',
            formData: {},
            success(res) {
              let data = JSON.parse(res.data)
              wx.hideLoading();
              if(data.code=='200'){
                let commodityImg = 'form.commodityImg'
              that.setData({
                [commodityImg]: data.data.path||''
              })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '图片上传失败'
                });
              }
              
            }
          })
      }
    }
    })
  },
  // 提交表单
  formSubmit: function (e) {
    if (this.validForm(e)) {
      let postbody = e.detail.value
      postbody.commodityTypeId = this.data.form.commodityTypeId
      postbody.commodityImg = this.data.form.commodityImg
      postbody.commoditySpecificationsDtos = this.data.form.commoditySpecificationsDtos||[]
      postbody.commodityChannelId = '1345252220928643073'
      if(this.data.id){
        API.editCommodity(this.data.id, postbody).then(res => {
          wx.navigateBack({});
          wx.showToast({
            icon: 'success',
            title: '修改成功',
            duration: 1500
          });
        }, err => {
          wx.hideLoading();
          // wx.showToast({
          //   icon: 'none',
          //   title: err || '修改失败'
          // });
        })
      }else{
        API.addCommodity(postbody).then(res => {
          wx.navigateBack({});
          wx.showToast({
            icon: 'success',
            title: '添加成功',
            duration: 1500
          });
        }, err => {
          wx.hideLoading();
          // wx.showToast({
          //   icon: 'none',
          //   title: err || '添加失败'
          // });
        })
      }
      
    }
  },//提交验证
  validForm(e) {
    var commodityName = e.detail.value.commodityName;
    var commodityImg = this.data.form.commodityImg;
    var commodityTypeId =  this.data.form.commodityTypeId;
  
    if (!commodityName || commodityName < 1) {
      wx.showToast({
        title: '商品姓名不能为空',
        icon: 'none'
      });
      return false;
    }
  
    if (!commodityImg) {
      wx.showToast({
        title: '商品图片不能为空',
        icon: 'none'
      });
      return false;
    }
    if (!commodityTypeId) {
      wx.showToast({
        title: '商品分类不能为空',
        icon: 'none'
      });
      return false;
    }
    return true;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id||null
    })
    this.getList()
    this.data.id&&this.getDetail()
    // console.log(222222222)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    let commoditySpecificationsDtos = wx.getStorageSync('commoditySpecificationsDtos')
    let str = 'form.commoditySpecificationsDtos'
    this.setData({
      [str]: commoditySpecificationsDtos||[]
    })
    // console.log(this.data.form.commoditySpecificationsDtos,1111111111111)

  },
  getList(){
    wx.showLoading ({});
    API.getProductType().then(res => {
      wx.hideLoading()
      this.setData({
        dataList: res.data||[]
      })
    }, err => {
      wx.hideLoading();
    })
  },
  getDetail(){
    wx.showLoading ({});
    API.getCommodityDetail(this.data.id).then(res => {
      wx.hideLoading()
      this.setData({
        form: res.data||[]
      })
      wx.removeStorageSync("commoditySpecificationsDtos")
      // wx.setStorageSync("commoditySpecificationsDtos", res.data.commoditySpecificationsDtos||[])
    }, err => {
      wx.hideLoading();
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
